package one;

import java.util.ArrayList;
import java.util.Stack;

/**
 * Given a binary tree, return the inorder traversal of its nodes' values.
 * <p>
 * For example:
 * Given binary tree {1,#,2,3},
 * <p>
 * 1
 * \
 * 2
 * /
 * 3
 * return [1,3,2].
 * <p>
 * Note: Recursive solution is trivial, could you do it iteratively?
 * <p>
 * <p>
 * =======================
 * iterative solution is interesting.
 * <p>
 * Solutions:
 * <p>
 * /**
 * Definition for binary tree
 * public class one.TreeNode {
 * int val;
 * one.TreeNode left;
 * one.TreeNode right;
 * one.TreeNode(int x) { val = x; }
 * }
 */

class TreeNode {
    int      val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}


public class Day04_Binary_Tree_Inorder_Traversal {
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        inOrder(root, res);
        return res;
    }

    /**
     * iterative solution
     *
     * @param root
     * @param res
     */
    private void inOrder(TreeNode root, ArrayList<Integer> res) {
        Stack<TreeNode> sts = new Stack<TreeNode>();
        TreeNode cur = root;
        while (!sts.empty() || cur != null) {
            if (cur != null) {
                sts.push(cur);
                cur = cur.left;
            } else {
                cur = sts.pop();
                res.add(cur.val);
                cur = cur.right;
            }
        }
    }

    /**
     * reccurence solution
     *
     * @param node
     * @param res
     */
    private void inorder(TreeNode node, ArrayList<Integer> res) {
        if (node == null) {
            return;
        }
        inorder(node.left, res);
        res.add(node.val);
        inorder(node.right, res);
    }
}
